<?php

namespace app\common\model;

use app\event\mobile\MobileSupplierSuccess;
use think\Exception;
use think\facade\Db;
use app\common\model\FinanceStat;
use think\facade\Log;

class Mobile
{
    /**
     * 处理话费订单状态回调更新.
     */
    public static function handleNotify($order, $update)
    {
        if (empty($update['finish_time'])) {
            $update['finish_time'] = time();
        }
        Db::name('mobile_order')
            ->where('id', $order['id'])
            // ->whereIn('supplier_status', [1, 2, 99])
            ->update($update);

        if (1 == $order['order_type']) {
            $prefix = 'slow_';
        } else {
            $prefix = 'fast_';
        }

        if (3 == $update['supplier_status']) {  // 充值成功
            // 充值成功
            Db::name('mobile_supplier_stat')
                ->where('mobile_supplier_id', $order['mobile_supplier_id'])
                ->inc('success_num', 1)
                ->inc($prefix . 'success_num', 1)
                ->update();

            // 成功了，插入财务明细
            FinanceStat::addSuccessRecord([
                'order_id' => $order['sub_order_id'],
                'order_type' => PRODUCT_MOBILE_SERV,
                'settle_type' => $order['settle_type'],
                'amount' => $order['amount'],
                'sale_price' => $order['sale_price'],
                'settle_price' => $order['settle_price'],
                'supplier_price' => $order['supplier_price'],
                'profit' => $order['sale_price'] - $order['settle_price'],
                'platform_profit' => $order['settle_price'] - $order['supplier_price'],
                'supplier_id' => $order['mobile_supplier_id'],
                'agent_id' => $order['agent_id'],
                'salesman_id' => $order['salesman_id'] ?? 0,
                'remark' => '充值成功',
            ]);

            //话费充值成功事件
            try {

                event(new MobileSupplierSuccess($order['order_id']));
                Log::info('话费充值成功触发 充值成功事件order_id:'.$order['order_id']);

            }catch (Exception $exception){
                Log::error($exception->getMessage());
            }


        } elseif (in_array($update['supplier_status'], [99, 4]) && empty($order['is_finish'])) {
            // 充值失败
            Db::name('mobile_supplier_stat')
                ->where('mobile_supplier_id', $order['mobile_supplier_id'])
                ->inc('fail_num', 1)
                ->inc($prefix . 'fail_num', 1)
                ->update();
        }

        if (empty($order['is_finish']) && $order['order_type'] == 2) {
            // 话费成功率统计【30分钟】，只统计快充的订单
            Db::name('mobile_order_stats')
                ->insert([
                    'mobile' => $order['mobile'],
                    'isp_type' => getMobileIsp($order['mobile']),
                    'amount' => fen2yuan($order['amount']),
                    'status' => $update['supplier_status'] == 3 ? 1 : 2,
                    'supplier_id' => $order['mobile_supplier_id'],
                    'agent_id' => $order['agent_id'],
                ]);
        }

        if (!empty($order['notify_url'])) {
            $agent = Db::name('agent')
                ->field('app_key, app_secret')
                ->where('id', $order['agent_id'])
                ->find();
            Db::name('mobile_notify_agent')
                ->insert([
                    'order_id' => $order['order_id'],
                    'notify_url' => $order['notify_url'],
                    'params' => json_encode([
                        'order_id' => strval($order['order_id']),
                        'out_order_id' => $order['out_order_id'],
                        'status' => $update['supplier_status'],
                        'mobile' => $order['mobile'],
                        'amount' => fen2yuan($order['amount']),
                        'app_key' => $agent['app_key'],
                        'app_secret' => $agent['app_secret'],
                        'official_sn' => $order['official_sn'] ?? '',
                    ]),
                    'status' => 1,
                    'send_time' => time(),
                    'result' => '',
                ]);
        }
    }
}
